
package com.yytek.gw.converter;

import com.alibaba.fastjson2.JSON;
import com.yytek.common.core.domain.DeviceCache;
import com.yytek.common.web.domain.ThingModelMessage;

import jdk.nashorn.api.scripting.NashornScriptEngine;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;


@Slf4j
@Data
public class ScriptConverter implements IConverter {
    //private final NashornScriptEngine engine = (NashornScriptEngine) (new ScriptEngineManager()).getEngineByName("nashorn");
    private final ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
    private Object scriptObj;

    @Override
    public void setScript(String script) {
        try {
            scriptObj = engine.eval(String.format("new (function () {\n%s})()", script));
        } catch (ScriptException e) {
            log.error("eval converter script error", e);
        }
    }
    @Override
    public Map<String, Object> decode(Object msg) {
        try {
            Invocable invoke = (Invocable)engine; // 调用merge方法，并传入两个参数
            Object rst = invoke.invokeMethod(scriptObj, "decode", msg);
            Map<String, Object> map = (Map<String, Object>) JSON.parse((String) rst);
            return map;
        } catch (Throwable e) {
            log.error("execute decode script error", e);
        }
        return null;
    }

    @Override
    public Object encode(Object msg, DeviceCache device){
        try {
            Invocable invoke = (Invocable)engine; // 调用merge方法，并传入两个参数
            Object result = invoke.invokeMethod(scriptObj, "encode", msg, device);
            return result;
        } catch (Throwable e) {
            log.error("execute encode script error", e);
        }
        return null;
    }

    @Override
    public void putScriptEnv(String key, Object value) {
        engine.put(key, value);
    }
}
